package com.leyou.service;

import com.aliyun.oss.OSS;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.MatchMode;
import com.aliyun.oss.model.PolicyConditions;
import com.leyou.constant.Constants;
import com.leyou.exception.LyException;
import com.leyou.exception.domain.ExceptionEnum;
import com.leyou.uploadconfig.OSSProperties;
import com.leyou.utils.BeanHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.context.annotation.ApplicationScope;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.*;


@Service
public class UploadService {

    //指定允许上传的mine类型
    private Set<String> allowPic = new HashSet<>(Arrays.asList(Constants.ALLOW_PIC));
    @Autowired
    private OSS client;

    @Autowired
    private OSSProperties ossProperties;

    public String uploadImage(MultipartFile file) {

        if (!allowPic.contains(file.getContentType())) {
            throw new LyException(ExceptionEnum.INVALID_FILE_TYPE);
        }
        //读文件流失败
        try {
            BufferedImage bufferedImage = ImageIO.read(file.getInputStream());
            if (bufferedImage == null) {
                throw new LyException(ExceptionEnum.INVALID_FILE_TYPE);
            }
        } catch (Exception e) {
            throw new LyException(ExceptionEnum.INVALID_FILE_TYPE);
        }

        String path = Constants.IMAGE_PATH;
        String name = UUID.randomUUID().toString() + file.getOriginalFilename();
        try {
            file.transferTo(new File(path, name));
        } catch (IOException e) {
            throw new LyException(ExceptionEnum.FILE_UPLOAD_ERROR);
        }
        return Constants.IMG_URL + name;
    }

    public Map<String, Object> getOasSignature() {
        long expireTime = ossProperties.getExpireTime();
        long expireEndTime = System.currentTimeMillis() + expireTime * 1000;
        Date expiration = new Date(expireEndTime);
        PolicyConditions policyConds = new PolicyConditions();
        policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, 1048576000);
        policyConds.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, ossProperties.getDir());

        String postPolicy = client.generatePostPolicy(expiration, policyConds);
        byte[] binaryData;
        try {
            binaryData = postPolicy.getBytes("utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            throw new LyException(ExceptionEnum.FILE_UPLOAD_ERROR);
        }
        String encodedPolicy = BinaryUtil.toBase64String(binaryData);
        String postSignature = client.calculatePostSignature(postPolicy);
        Map<String, Object> map = new HashMap<>();
        map.put("dir", ossProperties.getDir());
        map.put("accessId", ossProperties.getAccessKeyId());
        map.put("host", ossProperties.getHost());
        map.put("policy", encodedPolicy);
        map.put("signature", postSignature);
        map.put("expire", expireEndTime);
        return map;
    }


}
